package pers.jing.android.helper.model

import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper
import java.util.regex.Pattern

/**
 * 节点
 * 忽略的属性值: content-desc, package, NAF, checkable, focusable, focused, password, scrollable
 */
@JsonIgnoreProperties(ignoreUnknown = true)
data class UiNode(
    // 基础属性（均为 XML 属性）
    @field:JacksonXmlProperty(isAttribute = true)
    val index: Int = 0,

    /**
     * 当clasName是TextView时, text的值是TextView.getText
     */
    @field:JacksonXmlProperty(isAttribute = true)
    val text: String = "",

    @field:JacksonXmlProperty(localName = "resource-id", isAttribute = true) // 映射 "resource-id" 属性
    val resourceId: String = "",

    @field:JacksonXmlProperty(localName = "class", isAttribute = true)
    val clsName: String = "", // 注意 class 是 Kotlin 关键字，需用反引号或改名

    @field:JacksonXmlProperty(isAttribute = true)
    val bounds: String = "", // 格式如 "[x1,y1][x2,y2]"

    @field:JacksonXmlProperty(isAttribute = true)
    val enabled: Boolean = false,

    @field:JacksonXmlProperty(isAttribute = true)
    val selected: Boolean = false,

    @field:JacksonXmlProperty(isAttribute = true)
    val checked: Boolean = false,

    @field:JacksonXmlProperty(isAttribute = true)
    val clickable: Boolean = false,

    @field:JacksonXmlProperty(localName = "long-clickable", isAttribute = true)
    val longClickable: Boolean = false,

    // 嵌套的子节点（递归结构）
    @field:JacksonXmlProperty(localName = "node")
    @field:JacksonXmlElementWrapper(useWrapping = false)
    val children: List<UiNode> = emptyList()
) {
    fun getCenter(): Pair<Int, Int>? {
        if (bounds.isEmpty()) {
            return null
        }
        val pattern = Pattern.compile("\\[(\\d+),(\\d+)\\]\\[(\\d+),(\\d+)\\]")
        val matcher = pattern.matcher(bounds)
        if (matcher.matches()) {
            val x1 = matcher.group(1).toInt()
            val y1 = matcher.group(2).toInt()
            val x2 = matcher.group(3).toInt()
            val y2 = matcher.group(4).toInt()

            val cx = x1 + (x2 - x1) / 2
            val cy = y1 + (y2 - y1) / 2
            return Pair(cx, cy)
        }
        return null
    }
}